/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.raysdata.rdc.dataasset.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.raysdata.rdc.dataasset.dto.CatalogDTO;
import com.raysdata.rdc.dataasset.entity.LabelResourceRelation;
import com.raysdata.rdc.dataasset.entity.Industry;
import com.raysdata.rdc.dataasset.entity.Topic;
import com.raysdata.rdc.dataasset.enums.LabelRelationEnum;
import com.raysdata.rdc.dataasset.service.ILabelResourceRelationService;
import com.raysdata.rdc.dataasset.service.IIndustryService;
import com.raysdata.rdc.dataasset.service.ITopicService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.system.entity.DictBiz;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.raysdata.rdc.dataasset.entity.Catalog;
import com.raysdata.rdc.dataasset.vo.CatalogVO;
import com.raysdata.rdc.dataasset.service.ICatalogService;
import org.springblade.core.boot.ctrl.BladeController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *  控制器
 *
 * @author mengjingji
 * @since 2021-04-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/catalog")
@Api(value = "资产目录", tags = "资产目录接口")
public class CatalogController extends BladeController {
	private static Logger logger = LoggerFactory.getLogger(CatalogController.class);

	private final ICatalogService catalogService;
	private final ITopicService topicService;
	private final IIndustryService industryService;
	private final IDictBizClient dictBizClient ;
	private final ILabelResourceRelationService labelResourceRelationService ;
	private static IUserClient userClient;

	private static IUserClient getUserClient() {
		if (userClient == null) {
			userClient = SpringUtil.getBean(IUserClient.class);
		}
		return userClient;
	}


	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入catalog")
	public R<Catalog> detail(Long id) {
		Catalog detail = catalogService.getById(id);
		return R.data(detail);
	}

	/**
	 * 列表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "列表", notes = "传入catalog")
	public R<List<Catalog>> list(Catalog catalog, Query query) {
		List<Catalog> list = catalogService.list( Condition.getQueryWrapper(catalog));
		return R.data(list);
	}

	/**
	 * 自定义分页 
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入catalog")
	public R<IPage<CatalogVO>> page(CatalogVO catalog, Query query) {
		IPage<CatalogVO> pages = catalogService.selectCatalogPage(Condition.getPage(query), catalog);
		for(CatalogVO vo: pages.getRecords()){
			Topic topic = topicService.getById(vo.getTopicId());
			Optional.ofNullable(topic).ifPresent(p ->vo.setTopicName(p.getName()));
			Industry industry= industryService.getById(vo.getIndustryId());
			Optional.ofNullable(industry).ifPresent(p ->vo.setIndustryName(p.getName()));
			R<DictBiz> dictBiz=dictBizClient.getById(vo.getUpdateFrequencyDictId());
			logger.info(""+vo.getUpdateFrequencyDictId());
			logger.info("is null ? {}",dictBiz==null);
			if(null!=dictBiz){
				logger.info("obj is:{}",dictBiz);
			}
			Optional.ofNullable(dictBiz.getData()).ifPresent(p ->vo.setUpdateFrequencyDictName(p.getDictValue()));
			R<DictBiz> dictBiz2=dictBizClient.getById(vo.getShareTypeId());
			logger.info("obj is:{}",dictBiz2);
			Optional.ofNullable(dictBiz2.getData()).ifPresent(p ->vo.setShareTypeName(p.getDictValue()));
			R<User> r=getUserClient().userInfoById(vo.getCreateUser());
			logger.info("%s",r);
			Optional.ofNullable(r.getData()).ifPresent(u ->vo.setCreateUserName(u.getAccount()));
		}


		return R.data(pages);
	}

	private boolean saveLabelListRelation(CatalogDTO catalog){
		labelResourceRelationService.remove(Wrappers.<LabelResourceRelation>query().lambda().eq(LabelResourceRelation::getResourceId, catalog.getId()).eq(LabelResourceRelation::getResourceType, LabelRelationEnum.catalog.getName()));
		List<LabelResourceRelation> labelList = new ArrayList<>();
		catalog.getLabelList().forEach(labelId ->  {
			LabelResourceRelation labelResourceRelation = new LabelResourceRelation();
			labelResourceRelation.setResourceId(catalog.getId());
			labelResourceRelation.setResourceType(LabelRelationEnum.catalog.getName());
			labelResourceRelation.setLabelId(labelId);
			labelList.add(labelResourceRelation);
		});
		// 新增配置
		return  labelResourceRelationService.saveBatch(labelList);
	}

	/**
	 * 新增 
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入catalog")
	public R save(@Valid @RequestBody CatalogDTO catalog) {
		catalog.setCreateUser(getUser().getUserId());
		catalog.setCreateTime(LocalDateTime.now());

		catalog.setUpdateUser(getUser().getUserId());
		catalog.setUpdateTime(LocalDateTime.now());
		catalogService.save(catalog);
		saveLabelListRelation(catalog);
		return R.status(true);
	}

	/**
	 * 修改 
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入catalog")
	public R update(@Valid @RequestBody CatalogDTO catalog) {

		catalog.setUpdateUser(getUser().getUserId());
		catalog.setUpdateTime(LocalDateTime.now());
		catalogService.updateById(catalog);
		saveLabelListRelation(catalog);
		return R.status(true);
	}

	/**
	 * 新增或修改 
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入catalog")
	public R submit(@Valid @RequestBody CatalogDTO catalog) {
		if(catalog.getId()==null || catalog.getId().equals(0L)){
			catalog.setCreateUser(getUser().getUserId());
			catalog.setCreateTime(LocalDateTime.now());
		}
		catalog.setUpdateUser(getUser().getUserId());
		catalog.setUpdateTime(LocalDateTime.now());
		catalogService.saveOrUpdate(catalog);
		saveLabelListRelation(catalog);
		return R.status(true);
	}

	
	/**
	 * 删除 
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(catalogService.removeByIds(Func.toLongList(ids)));
	}

	/**
	 * 资源目录共享占比统计
	 */
	@GetMapping("/statistics-catalog-share-type-ratio")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "资源目录共享占比统计", notes = "资源目录共享占比统计")
	public R<List<Object>> statisticsCatalogShareTypeRatio() {
		List<Object> list = catalogService.statisticsCatalogShareTypeRatio( );
		return R.data(list);
	}


	/**
	 * 数据量前十
	 */
	@GetMapping("/top10")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "资源目录数据量前十", notes = "资源目录数据量前十")
	public R<List<CatalogVO>> top10() {
		List<CatalogVO> list = catalogService.top10();
		return R.data(list);
	}



}
